<template>
	<video
		id="video"
		:autoplay="state.autoplay"
		:controls="state.controls"
		:playsinline="state.playsinline"
		:muted="state.muted"
		style="width: 100%; height: 100%"
	></video>
</template>
<script lang="ts" setup>
import { useAttrs } from "element-plus";
const state = reactive({
	autoplay: true,
	controls: true,
	muted: true,
	playsinline: false
});
onMounted(() => {
	videoPlayer();
});
let attrs = useAttrs();
const videoPlayer = () => {
	function init(stream?: any) {
		// eslint-disable-next-line @typescript-eslint/no-unused-vars
		let isDev = import.meta.env.DEV;
		console.log(attrs.value.videoUrl);
		// support api_path
		// const baseUrl = location.origin + location.pathname.substr(0, location.pathname.lastIndexOf("/"));
		// const ws = new WebSocket(`ws${baseUrl.substr(4)}/webrtc/api/ws${location.search || "?src=office"}`);
		// const ws = new WebSocket(`ws://localhost/webrtc/api/ws${location.search || "?src=office"}`);
		// const ws = new WebSocket(`ws://localhost/applet/stream/ssiot-gw-camera/api/ws?src=camera2f.ch1`);

		const ws = new WebSocket(`ws://${isDev ? "localhost:3038" : window.location.host}${attrs.value.videoUrl}`, [
			// `${GlobalStore().token}`
		]);
		ws.onopen = () => {
			pc.createOffer().then(offer => {
				pc.setLocalDescription(offer).then(() => {
					console.log(offer.sdp);
					const msg = { type: "webrtc/offer", value: pc.localDescription?.sdp };
					ws.send(JSON.stringify(msg));
				});
			});
		};
		ws.onmessage = ev => {
			const msg = JSON.parse(ev.data);
			console.debug("ws.onmessage", msg);

			if (msg.type === "webrtc/candidate") {
				pc.addIceCandidate({ candidate: msg.value, sdpMid: "0" });
			} else if (msg.type === "webrtc/answer") {
				pc.setRemoteDescription({ type: "answer", sdp: msg.value });
			}
		};

		const pc = new RTCPeerConnection({
			iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
		});
		pc.onicecandidate = ev => {
			console.debug("pc.onicecandidate", ev.candidate);

			if (ev.candidate !== null) {
				ws.send(
					JSON.stringify({
						type: "webrtc/candidate",
						value: ev.candidate.toJSON().candidate
					})
				);
			}
		};
		pc.ontrack = ev => {
			const video: any = document.getElementById("video");
			console.debug("pc.ontrack", video.srcObject !== null);

			// when audio track not exist in Chrome
			if (ev.streams.length === 0) return;

			// when audio track not exist in Firefox
			if (ev.streams[0].id[0] === "{") return;

			// when stream already init
			if (video.srcObject !== null) return;

			video.srcObject = ev.streams[0];
		};

		// Safari don't support "offerToReceiveVideo"
		// so need to create transeivers manually
		pc.addTransceiver("video", { direction: "recvonly" });
		pc.addTransceiver("audio", { direction: "recvonly" });

		if (stream) {
			// stream.getTracks().forEach((track: any) => {
			// eslint-disable-next-line @typescript-eslint/no-unused-vars
			// const sender = pc.addTrack(track, stream);
			// track.stop();
			// setTimeout(() => {
			//     navigator.mediaDevices.getUserMedia({audio: true}).then(stream => {
			//         stream.getTracks().forEach(track => {
			//             sender.replaceTrack(track);
			//         });
			//     });
			// }, 10000);
			// });
		}
	}

	if (navigator.mediaDevices) {
		navigator.mediaDevices
			.getUserMedia({ audio: true })
			.then(init)
			.catch(() => init());
	} else {
		init();
	}
};
</script>
